new Vue({
    el: '#app',
    data: {
        chatHistory: [],
        conversations: [],
        currentConversation: null, // 当前选中的对话
        usernameDb: '',
        passwordDb: '',
        dbUploadedFileName: '', // 用于存储上传的文件名
        urlDb: '',
        databaseName: '',
        inputMessage: '',
        username: '登录',
        showMenu: false,
        showLogin: false,
        showDatabase: false,
        menuVisible: false,
        isLoggedIn: true,
        password: '',
        connectedDatabases: []
    },
    mounted() {
        // 从 localStorage 获取数据库登录信息
        this.urlDb = localStorage.getItem('db_url') || '';
        this.usernameDb = localStorage.getItem('db_username') || '';
        this.passwordDb = localStorage.getItem('db_password') || '';
        this.username = '开始';

        // 更新用户名到页面
        const usernameDisplay = document.getElementById('username-display');
        if (usernameDisplay) {
            usernameDisplay.textContent = this.username;
        }

        // 初始化时加载已保存的数据库列表
        try {
            this.connectedDatabases = JSON.parse(localStorage.getItem('connected_databases')) || [];
        } catch (error) {
            this.connectedDatabases = [];
        }

        // 加载当前用户的对话历史
        this.loadChatHistory();

    },
    updated() {
        this.$nextTick(() => {
            this.currentConversation.messages.forEach((message, index) => {
                if (message.chart && !message.chart.rendered) {
                    console.log(`正在渲染消息索引为 ${index} 的图表`);
                    const chartRef = this.$refs[`chart-${index}`];
                    if (chartRef && chartRef.length > 0) {
                        const chartDom = chartRef[0];
                        console.log(`图表 DOM 尺寸: ${chartDom.clientWidth}x${chartDom.clientHeight}`);
                        // 初始化 ECharts 实例，并应用主题（如有）
                        const myChart = echarts.init(chartDom, 'macarons'); // 如果没有使用主题，可以省略第二个参数
                        myChart.setOption(message.chart.option);
                        myChart.resize(); // 调整图表大小
                        // 标记图表为已渲染，避免重复初始化
                        this.$set(this.currentConversation.messages[index].chart, 'rendered', true);
                        console.log(`图表已渲染: chart-${index}`);
                    } else {
                        console.log(`未找到图表引用: chart-${index}`);
                    }
                }
            });
        });
    },
    methods: {
        loadChatHistory() {
            if (this.username && this.username !== '开始') {
                const storedConversations = JSON.parse(localStorage.getItem(`conversations_${this.username}`)) || [];
                this.conversations = storedConversations;
                if (this.conversations.length > 0) {
                    this.currentConversation = this.conversations[0];
                } else {
                    // 如果没有对话，自动创建一个默认对话
                    this.addNewConversation('默认对话');
                }
            }
            if (this.conversations.length > 0) {
                this.currentConversation = this.conversations[0];
            } else {
                // 如果没有对话，自动创建一个默认对话
                this.addNewConversation('默认对话');
            }
        },
        saveChatHistory() {
            if (this.username && this.username !== '开始') {
                localStorage.setItem(`conversations_${this.username}`, JSON.stringify(this.conversations));
            }
        },
        addNewConversation(name) {
            const newConv = {
                id: Date.now() + Math.random(), // 添加唯一 ID
                name: name || `对话${this.conversations.length + 1}`,
                messages: []
            };
            this.conversations.push(newConv);
            this.currentConversation = newConv;
            this.saveChatHistory();
        },
        deleteConversation(index) {
            if (this.conversations.length == 1) {
                alert("必须至少保留一个对话");

            }
            else if (confirm(`确定要删除对话 "${this.conversations[index].name}" 吗？`)) {
                // 如果要删除的是当前对话，切换到另一个对话
                const isCurrent = this.currentConversation === this.conversations[index];
                this.conversations.splice(index, 1);
                this.saveChatHistory();

                if (isCurrent) {
                    if (this.conversations.length > 0) {
                        this.currentConversation = this.conversations[0];
                    } else {
                        this.currentConversation = null;
                    }
                }
            }
        },
        addConversationPrompt() {
            let convName = prompt("请输入新对话的名称:", `对话${this.conversations.length + 1}`);
            if (convName) {
                // 检查是否有重复名称
                const exists = this.conversations.some(conv => conv.name === convName);
                if (exists) {
                    alert("该对话名称已存在，请选择其他名称。");
                } else {
                    this.addNewConversation(convName);
                }
            }
        },
        renameConversation(index) {
            let newName = prompt("请输入新的对话名称:", this.conversations[index].name);
            if (newName) {
                // 检查是否有重复名称
                const exists = this.conversations.some((conv, idx) => conv.name === newName && idx !== index);
                if (exists) {
                    alert("该对话名称已存在，请选择其他名称。");
                } else {
                    this.updateConversationName(index, newName);
                }
            }
        },
        updateConversationName(index, newName) {
            if (newName && this.conversations[index]) {
                this.conversations[index].name = newName;
                this.saveChatHistory();
            }
        },
        selectConversation(conv) {
            this.currentConversation = conv;
        },
        saveDatabaseConfig() {
            // 保存数据库配置到 localStorage
            localStorage.setItem('db_url', this.urlDb);
            localStorage.setItem('db_username', this.usernameDb);
            localStorage.setItem('db_password', this.passwordDb);
            alert('数据库配置已保存');

            // 同时保存已连接的数据库列表
            localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
        },
        addDatabase() {
            // 使用 localStorage 中的账号密码进行添加数据库操作
            if (!this.databaseName) {
                alert('请输入数据库名称');
                return;
            }

            const params = new URLSearchParams([
                ['url', this.urlDb],
                ['username', this.usernameDb],
                ['password', this.passwordDb],
                ['database', this.databaseName]
            ]);

            fetch(`http://localhost:8080/Database/AddDatabase?${params.toString()}`, {
                method: 'GET', // 保留 GET 方法
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded' // 因为我们现在使用查询字符串
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert('数据库添加成功');

                        // 添加到前端数据库列表
                        this.connectedDatabases.push({
                            name: this.databaseName,
                            url: this.urlDb,
                            username: this.usernameDb,
                            password: this.passwordDb
                        });

                        // 清空输入框
                        this.databaseName = '';

                        // 同时保存已连接的数据库列表
                        localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
                    } else {
                        alert('数据库添加失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    alert('请求失败: ' + error.message);
                });
        },
        removeDatabase(databaseName) {
            // 使用 localStorage 中的账号密码进行删除数据库操作
            if (!databaseName) {
                alert('无法识别要删除的数据库名称');
                return;
            }

            // 构建查询参数
            const params = new URLSearchParams([
                ['url', this.urlDb],
                ['username', this.usernameDb],
                ['password', this.passwordDb],
                ['database', databaseName]
            ]);

            // 将查询参数附加到URL上
            fetch(`http://localhost:8080/Database/RemoveDatabase?${params.toString()}`, {
                method: 'GET', // 更改为 GET 方法
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded' // 这一行实际上不需要，因为我们没有请求体
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert('数据库删除成功');

                        // 从前端数据库列表中移除
                        this.connectedDatabases = this.connectedDatabases.filter(db => db.name !== databaseName);

                        // 同时保存已连接的数据库列表
                        localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
                    } else {
                        alert('数据库删除失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    alert('请求失败: ' + error.message);
                });
        },
        async sendMessage() {
            if (this.inputMessage.trim() !== '') {
                // 将用户输入的消息添加到当前对话中
                this.currentConversation.messages.push({ text: this.inputMessage, user: true, isTable: false, chart: null });
                this.saveChatHistory();

                const userMessage = this.inputMessage;
                this.inputMessage = '';

                try {
                    const response = await fetch('http://localhost:8080/textAnalysis', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ message: userMessage })
                    });

                    if (!response.ok) {
                        throw new Error(`Server error: ${response.statusText}`);
                    }

                    const contentType = response.headers.get('Content-Type');
                    let responseData = await response.text();
                    console.log('Response data (Text):', responseData);

                    // 判断返回的纯文本是否为 JSON 格式
                    try {
                        const jsonData = JSON.parse(responseData);
                        console.log('Parsed JSON data:', jsonData);

                        // 检查是否需要绘制图表
                        const shouldDrawChart = userMessage.includes('图') ||
                            userMessage.includes('柱状图') ||
                            userMessage.includes('饼图') ||
                            userMessage.includes('折线图');

                        if (shouldDrawChart && Array.isArray(jsonData) && jsonData.length > 0) {
                            // 确定图表类型
                            let chartType = 'bar'; // 默认柱状图
                            if (userMessage.includes('饼图')) {
                                chartType = 'pie';
                            } else if (userMessage.includes('折线图')) {
                                chartType = 'line';
                            }

                            // 生成图表配置
                            const chartOption = this.generateChartOption(chartType, jsonData);
                            console.log('Generated Chart Option:', JSON.stringify(chartOption, null, 2));

                            // 将图表配置添加到消息中
                            this.currentConversation.messages.push({ text: '', user: false, isTable: false, chart: { type: chartType, option: chartOption, rendered: false } });
                            this.saveChatHistory();

                        } else if (Array.isArray(jsonData) && jsonData.length > 0) {
                            // 动态生成表格
                            const tableHeaders = Object.keys(jsonData[0]);
                            let tableHTML = `
                                <table class="table table-bordered table-striped table-hover table-sm custom-table">
                                    <thead class="thead-dark">
                                        <tr>
                            `;
                            tableHeaders.forEach(header => {
                                tableHTML += `<th>${header}</th>`;
                            });
                            tableHTML += `
                                        </tr>
                                    </thead>
                                    <tbody>
                            `;
                            jsonData.forEach(row => {
                                tableHTML += `<tr>`;
                                tableHeaders.forEach(header => {
                                    tableHTML += `<td>${row[header]}</td>`;
                                });
                                tableHTML += `</tr>`;
                            });
                            tableHTML += `</tbody></table>`;

                            // 将表格作为消息推送，并标记为表格
                            this.currentConversation.messages.push({ text: tableHTML, user: false, isTable: true, chart: null });
                            this.saveChatHistory();
                        } else if (typeof jsonData === 'object' && jsonData !== null) {
                            // 将对象作为普通文本显示
                            this.currentConversation.messages.push({ text: JSON.stringify(jsonData, null, 2), user: false, isTable: false, chart: null });
                            this.saveChatHistory();
                        } else {
                            this.currentConversation.messages.push({ text: 'No data available or invalid JSON response.', user: false, isTable: false, chart: null });
                            this.saveChatHistory();
                        }
                    } catch (error) {
                        // 如果解析为JSON失败，认为是普通文本
                        console.log('Not a JSON response, treating as plain text.');
                        this.currentConversation.messages.push({ text: responseData, user: false, isTable: false, chart: null });
                        this.saveChatHistory();
                    }

                } catch (error) {
                    console.error('Fetch error:', error);
                    this.currentConversation.messages.push({ text: `Network error occurred: ${error.message}`, user: false, isTable: false, chart: null });
                    this.saveChatHistory();
                }
            }
        },
        showLoginDialog() {
            this.showLogin = true;
            this.showMenu = false; // 隐藏选择框
        },
        showDatabaseConfig() {
            if (!this.isLoggedIn) {
                alert("请先登录");
                return;
            }
            this.showDatabase = true;
            this.showMenu = false; // 隐藏选择框
        },
        logout() {
            this.isLoggedIn = false;
            this.showMenu = false; // 隐藏选择框
        },
        async handleLogin(event) {
            try {
                const response = await fetch('http://localhost:8080/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_name: this.username,
                        password: this.password
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                console.log("收到响应，开始解析JSON...");
                const data = await response.json();
                console.log("解析后的数据:", data);

                if (data.code === 1 && data.msg === "success") {
                    localStorage.setItem('username', this.username);
                    this.isLoggedIn = true;
                    this.showLogin = false;
                    alert("登录成功！");
                    this.loadChatHistory();
                } else {
                    alert("登录失败，请检查用户名或密码");
                }
            } catch (error) {
                console.error("登录错误:", error);
                alert("登录失败，请检查网络连接或尝试重新加载页面");
            }
        },

        toggleMenu(event) {
            this.menuVisible = !this.menuVisible;
            if (this.menuVisible) {
                document.addEventListener('click', this.handleClickOutside);
            } else {
                document.removeEventListener('click', this.handleClickOutside);
            }
        },

        handleClickOutside(event) {
            const menu = this.$refs.menu; // 参考菜单元素
            const avatar = event.target.closest('.user-info'); // 参考头像元素
            if (menu && !menu.contains(event.target) && !avatar) {
                this.menuVisible = false;
                document.removeEventListener('click', this.handleClickOutside);
            }
        },
        // 生成 ECharts 配置的方法
        generateChartOption(type, data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.error('Invalid data for chart generation.');
                return {};
            }

            const keys = Object.keys(data[0]);
            if (keys.length < 2) {
                console.error('Data does not have enough keys for chart generation.');
                return {};
            }

            const categories = data.map(item => item[keys[0]]);
            const values = data.map(item => item[keys[1]]);
            console.log('Categories:', categories);
            console.log('Values:', values);

            // 定义颜色主题
            const colorPalette = ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'];

            let option = {
                color: colorPalette,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow' // 改为阴影指示器
                    },
                    backgroundColor: 'rgba(50,50,50,0.7)',
                    textStyle: {
                        color: '#fff'
                    }
                },
                legend: {
                    textStyle: {
                        color: '#333'
                    },
                    top: '10%' // 确保图例位于顶部
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%', // 增加底部留白以放置标题
                    containLabel: true
                },
                series: []
            };

            switch (type) {
                case 'bar':
                    option.title = {
                        text: '柱状图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'bar',
                        data: values,
                        itemStyle: {
                            barBorderRadius: [5, 5, 0, 0],
                            shadowColor: 'rgba(0,0,0,0.1)',
                            shadowBlur: 10
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'pie':
                    option.title = {
                        text: '饼图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.tooltip = {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    // 饼图不需要x轴和y轴
                    delete option.xAxis;
                    delete option.yAxis;
                    option.series.push({
                        name: keys[1],
                        type: 'pie',
                        radius: '50%',
                        data: data.map(item => ({ name: item[keys[0]], value: item[keys[1]] })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        label: {
                            formatter: '{b}: {c} ({d}%)',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'line':
                    option.title = {
                        text: '折线图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.tooltip = {
                        trigger: 'axis',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'line',
                        data: values,
                        smooth: false, // 平滑曲线
                        symbol: 'circle',
                        symbolSize: 8,
                        lineStyle: {
                            width: 3
                        },
                        areaStyle: {
                            color: 'rgba(84, 112, 198, 0.2)'
                        },
                        itemStyle: {
                            color: '#5470C6'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                default:
                    console.error('Unsupported chart type:', type);
            }

            console.log('Chart Option:', option);
            return option;
        },

        async handleFileUpload(event) {
            const file = event.target.files[0]; // 获取上传的文件
            if (file) {
                console.log('File uploaded:', file.name);

                // 创建 FormData 用于上传文件
                const formData = new FormData();
                formData.append('file', file); // 将文件添加到 formData

                try {
                    // 使用 fetch 上传文件到后端接口
                    const response = await fetch('http://localhost:8080/File/InformationExtraction', {
                        method: 'POST',
                        body: formData // 发送 FormData，包含文件
                    });

                    if (response.ok) {
                        // 添加成功接收文件的消息到聊天记录
                        this.currentConversation.messages.push({ text: `已接收文件: ${file.name}`, user: false, isTable: false, chart: null });

                        // 获取服务器返回的文本信息
                        // const resultText = await response.text();

                        // // 显示服务器返回的文本信息
                        // this.messages.push({ text: resultText, user: false, isTable: false, chart: null });
                    } else {
                        console.error('Server error:', response.statusText);
                        this.currentConversation.messages.push({ text: '文件上传失败，服务器错误。', user: false, isTable: false, chart: null });
                    }
                } catch (error) {
                    console.error('Fetch error:', error);
                    this.currentConversation.messages.push({ text: '网络错误，文件上传失败。', user: false, isTable: false, chart: null });
                }
            }
        },
        triggerDbFileUpload() {
            this.$refs.dbFileInput.click();
        },
        handleDbFileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                console.log('上传的文件:', file);
                this.dbUploadedFile = file;
                this.dbUploadedFileName = file.name; // 更新上传的文件名
            }
        },
    },
    watch: {
        // 监听 currentConversation 的变化，确保视图更新
        currentConversation(newConv) {
            // 由于我们直接在模板中绑定 currentConversation.messages，无需额外操作
        },
        // 移除对 messages 的深度监听
    }
});

